package ly.gupao.edu.thread.ExecuteByOrder;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: liyang
 * @date：2019/3/11 0011
 * describe：
 */
public class LockCondition {

    private static Lock lock = new ReentrantLock();
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();
    private static Condition condition3 = lock.newCondition();
    private static int count = 0;

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            while(true){
                lock.lock();
                try {
                    while(count % 3 != 0){
                        condition1.await();
                    }
                    System.out.println("Thread1 ---:" + count);
                    count++;
                    condition2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                lock.unlock();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            while(true){
                lock.lock();
                try {
                    while(count % 3 != 1){
                        condition2.await();
                    }
                    System.out.println("Thread2 ---:" + count);
                    count++;
                    condition3.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        });
        Thread t3 = new Thread(() -> {
            while(true){
                lock.lock();
                try {
                    while(count % 3 != 2){
                        condition3.await();
                    }
                    System.out.println("Thread3 ---:" + count);
                    count++;
                    condition1.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }



}
